package com.controller;

import com.config.MainInitializer;
import com.entity.Employee;
import com.entity.Salary;
import com.form.EmployeeInfo;
import com.form.Message;
import com.service.DrawingBedService;
import com.service.EmployeeService;
import com.service.SalaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;

@Controller
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    EmployeeService employeeService;
    @Autowired
    SalaryService salaryService;

    @Autowired
    DrawingBedService drawingBedService;

    /**
     * 获取员工登陆页面
     *
     * @param request  the request
     * @param Response the response
     * @return the string
     */
    @GetMapping(value = "/login")
    public String doLogin(HttpServletRequest request, HttpServletResponse Response) {

        boolean hasCookies = false;
        HttpSession session = request.getSession();
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for(Cookie cookie :cookies){
                if(cookie.getName().equals("Logged")){
                    if(cookie.getValue().equals("true")){
                        hasCookies = true;
                        break;
                    }
                }
            }
        }
        //没有cookies
        if (hasCookies) {
            return "employeeInfo";
        }
        //cookies
        else {
            Message message = new Message(0,"您尚未登录！请先登录。");
            return "index";

        }
    }
    /**
     * 实现员工登录
     *
     * @param username the username
     * @param password the password
     * @param session  the session
     * @param response the response
     * @return the string
     */
    @PostMapping(value = "/login")
    public String doLogin(@RequestParam(value = "username", defaultValue = "") String username,
                          @RequestParam(value = "password", defaultValue = "") String password,
                          HttpSession session, HttpServletResponse response, Model model) {

        //判断是否已经登录
        Employee employee = (Employee)session.getAttribute("employee");
        if(employee != null){
            Message message = new Message(0,"您已登录，请勿重复登录。请先退出后再登录。");
            model.addAttribute("message",message);
            return "index";
        }
        //从数据库中查找用户信息
        employee = employeeService.findByUserNameAndPwd(username, password);
        if (employee != null) {
            //登陆成功，返回managerView页面
            session.setAttribute("employee", employee);
            EmployeeInfo info = employeeService.findInfoByUsername(employee.getUsername());
            model.addAttribute("employeeInfo",info);
            Cookie cookie = new Cookie("Logged", employee.getUsername());
            cookie.setMaxAge(24 * 60 * 60);
            response.addCookie(cookie);
            return "employeeInfo";
        } else {
            //登陆失败，返回loginErr页面
            System.out.println(username);
            System.out.println(password);
            Message message = new Message(0,"The password not right.");
            model.addAttribute("message",message);
            return "index";
        }
    }
    /**
     * 注销登录
     *
     * @param request  the request
     * @param response the response
     * @return the string
     */
    @GetMapping(value = "/logout")
    public String doLogout(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        Cookie[] cookies = request.getCookies();
        request.getSession().removeAttribute("employee");
        //导致一个人登出全部cookies失效
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("Logged")) {
                cookie.setValue(null);
                cookie.setMaxAge(0);// 立即销毁cookie
                cookie.setPath("/");
                response.addCookie(cookie);
                break;
            }
        }
        return "index";
    }
    /**
     * 自己的信息页面
     *
     * @param session the session
     * @param model   the model
     * @return the string
     */
    @GetMapping("/employeeInfo")
    public String checkMyInfo(HttpSession session, Model model) {
        Employee employee = (Employee) session.getAttribute("employee");
        Message message = (Message) session.getAttribute("message");

        if(message!=null){
            model.addAttribute("message",message);
            session.removeAttribute("message");
        }
        if (employee == null) {
            message = new Message(0,"您尚未登录！请先登录。");
            model.addAttribute("message",message);
            System.out.println(message.getMessage());
            return "index";
        }
        EmployeeInfo info = employeeService.findInfoByUsername(employee.getUsername());
        System.out.println(info.toString());
        model.addAttribute("employeeInfo", info);
        return "employeeInfo";
    }

    /**
     * 查看自己的工资列表
     *
     * @param pageNo   the page no
     * @param pageSize the page size
     * @param session  the session
     * @param model    the model
     * @return the string
     */
    @GetMapping(value = "/salary")
    public String checkMySalary(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                                @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                HttpSession session, Model model) {
        if (pageSize <= 0) {
            pageSize = 10;
        }
        Employee employee = (Employee) session.getAttribute("employee");
        if (employee == null) {
            return "index";
        }
        PaginationSupport<Salary> salarys = employeeService.checkSalaryByName((int) employee.getEmployeeId(), pageNo, pageSize);
        model.addAttribute("salaryList", salarys);
        return "salaryInfo";
    }

    /**
     * 更新自己的用户信息
     *
     * @param fullname    the fullname
     * @param email       the email
     * @param birthday    the birthday
     * @param phoneNumber the phone number
     * @param bankAccount the bank account
     * @param session     the session
     * @param model       the model
     * @return the string
     */
    @PostMapping(value = "/updateInfo")
    public String updateEmployeeInfo(@RequestParam("fullname") String fullname,
                                     @RequestParam("email") String email,
                                     @RequestParam(value = "birthday",required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date birthday,
                                     @RequestParam("phoneNumber") String phoneNumber,
                                     @RequestParam("bankAccount") String bankAccount,
                                     HttpSession session, Model model) {
        Employee employee = (Employee) session.getAttribute("employee");
        employee.setFullname(fullname);
        employee.setEmail(email);
        if(birthday!=null){
            employee.setBirthday(new Timestamp(birthday.getTime()));
        }
        employee.setPhoneNumber(phoneNumber);
        employee.setBankAccount(bankAccount);
        session.setAttribute("employee",employee);
        Message message=employeeService.updateEmployeeInfo(employee);
        session.setAttribute("message",message);
        return "redirect:employeeInfo";
    }

    /**
     * 更改头像图片
     *
     * @param file the file
     * @return the string
     */
    @PostMapping(value = "/updatePhoto")
    public String updateEmployeePhoto(@RequestParam("employeePhoto") MultipartFile file,Model model,HttpSession session) throws IOException {
        Employee employee = (Employee) session.getAttribute("employee");
        String name = file.getOriginalFilename();
        //只支持三种类型的图片
        if(!name.endsWith(".jpeg") && !name.endsWith(".jpg") && !name.endsWith(".png")){
            model.addAttribute("message",new Message(1,"The file type does not meet the requirements."));
            return "employeeInfo";
        }
        File fileObj = new File(name);
        try {
            file.transferTo(fileObj);
        } catch (IOException e) {

        }
        String path = MainInitializer.uploadLocalPath+"/"+name;
        path = path.replaceAll("\\\\","/");
        String url=drawingBedService.drawBed(path);
        Message message=employeeService.updatePhotoByUsername(employee.getUsername(),url);
        System.out.println(url);
        System.out.println("user photo have trans to" + fileObj.getAbsolutePath());
        return "employeeInfo";
    }
    /**
     * 通过年份和月份查找一个人的工资记录
     *
     * @param pageNo   the page no
     * @param pageSize the page size
     * @param year     the year
     * @param month    the month
     * @param session  the session
     * @param model    the model
     * @return the string
     */
    @GetMapping("/findSalaryByYearAndMonth")
    public String findSalaryByYearAndMonth(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                                           @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                           @RequestParam(value = "year",defaultValue = "0") int year,
                                           @RequestParam(value = "month",defaultValue = "0") int month,
                                           HttpSession session,Model model){
        Employee employee = (Employee)session.getAttribute("employee");
        if(year==0 && month == 0){
            return "redirect:salary";
        }else if(month==0 && year!=0){
            PaginationSupport<Salary> salarys = salaryService.findSalaryByYear(employee.getEmployeeId(),year,
                    pageNo,pageSize);
            model.addAttribute("salaryList",salarys);
            System.out.println(salarys.getItems().toString());
        }else if(month!=0 && year==0){
            PaginationSupport<Salary> salarys = salaryService.findSalaryByMonth(employee.getEmployeeId(),month,
                    pageNo,pageSize);
            model.addAttribute("salaryList",salarys);
            System.out.println(salarys.getItems().toString());
        }else{
            PaginationSupport<Salary> salarys = salaryService.findSalaryByYearAndMonth(employee.getEmployeeId(),year,month,
                    pageNo,pageSize);
            model.addAttribute("salaryList",salarys);
            System.out.println(salarys.getItems().toString());
        }
        return "salaryInfo";
    }
}
